package com.morningstar.system.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.morningstar.common.result.ServiceCheckResult;
import com.morningstar.system.dao.entity.SysRole;
import com.morningstar.system.dao.mapper.SysRoleMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 角色信息表 服务实现类
 * </p>
 *
 * @author yanglianshan
 * @since 2023-06-28
 */
@Slf4j
@Service
public class SysRoleService extends ServiceImpl<SysRoleMapper, SysRole> {

    @Resource
    private SysRoleMapper roleMapper;

    /**
     * 获取用户角色名称列表
     *
     * @param userId 用户Id
     * @return 用户角色key列表
     */
    public List<String> selectUserRoleKeys(Long userId) {
        return roleMapper.selectUserRoles(userId).stream().map(SysRole::getRoleKey).toList();
    }

    /**
     * 添加或更新角色 前校验
     *
     * @param sysRole 系统用户
     * @return 校验结果
     */
    public ServiceCheckResult checkAddAndUpdate(SysRole sysRole) {
        LambdaQueryWrapper<SysRole> checkRoleNameWrapper = new LambdaQueryWrapper<SysRole>()
                .eq(SysRole::getRoleName, sysRole.getRoleName())
                .ne(sysRole.getRoleId() != null, SysRole::getRoleId, sysRole.getRoleId());
        if (this.count(checkRoleNameWrapper) > 0) {
            return new ServiceCheckResult(true, "角色名称已存在");
        }
        LambdaQueryWrapper<SysRole> checkRoleKeyWrapper = new LambdaQueryWrapper<SysRole>()
                .eq(SysRole::getRoleKey, sysRole.getRoleKey())
                .ne(sysRole.getRoleId() != null, SysRole::getRoleId, sysRole.getRoleId());
        if (this.count(checkRoleKeyWrapper) > 0) {
            return new ServiceCheckResult(true, "角色编码已存在");
        }
        return new ServiceCheckResult(false);
    }
}
